﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace Rung.Soft.Jx3Tookit.Addon.AutoPress.Utility
{
    public static class SerializeHelper
    {
        public static void Serialize(object o, string fullFileName)
        {
            // 保证路径存在
            FileInfo fi = new FileInfo(fullFileName);
            if (!Directory.Exists(fi.DirectoryName))
            {
                Directory.CreateDirectory(fi.DirectoryName);
            }

            // 保存
            using (FileStream fileStream = new FileStream(fullFileName, FileMode.Create))
            {
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(fileStream, o);
                fileStream.Close();
            }
        }

        public static T DeSerialize<T>(string fullFileName, SerializationBinder binder) where T : class
        {
            using (FileStream fileStream = new FileStream(fullFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                BinaryFormatter b = new BinaryFormatter();
                if (null != binder) b.Binder = binder;

                try
                {
                    return b.Deserialize(fileStream) as T;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        public static T DeSerialize<T>(string fullFileName) where T : class
        {
            return DeSerialize<T>(fullFileName, null);
        }
    }
}
